﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web;
using Common;
using Common.Objects;
using Common.Objects.Enums;
using Common.WebApplication;
using EYCmsAdmin.Presentation.IPresentationServices;
using EYCmsAdmin.Presentation.Models.UserModels;
using Ninject;

namespace EYCmsAdmin.Presentation.FilterAttributes
{
    public class PermissionAttribute : AuthorizeAttribute
    {
        private readonly Roles role;

        private readonly Permissions[] userPermissions;

        public PermissionAttribute(Roles role, Permissions[] permissions)
        {
            this.role = role;
            userPermissions = permissions;
        }

        public PermissionAttribute(Roles role)
        {
            this.role = role;
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool result = base.AuthorizeCore(httpContext);
            var container = Ioc.Container;
            if(result)
            {
                var userPresentationService = container.Get<IUserPresentationService>();
                SystemUser loggedUser = BaseApplication.GetLoggedUser();
                if (loggedUser != null)
                {
                    UserLoginModel user = userPresentationService.UserLogOn(loggedUser.Login);
                    if(user.Roles.Contains(role))
                    {
                        if (userPermissions != null)
                        {
                            return CheckPermission(user.Permissions);
                        }

                        return true;
                    }
                }

                return false;
            }

            return false;
        }

        private bool CheckPermission(IList<Permissions> permissions)
        {
            return !userPermissions.Any(item => !permissions.Contains(item));
        }
    }
}